package com.kongjs.online.preview.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PdfUtils {
    public static List<File> pdfToImage(File pdf, int dpi) throws IOException {
        String pdfFilename = pdf.getName();
        PDDocument document = PDDocument.load(pdf);
        PDFRenderer pdfRenderer = new PDFRenderer(document);
        int pageCounter = 0;
        List<File> files = new ArrayList<>();
        for (PDPage ignored : document.getPages()) {
            BufferedImage bim = pdfRenderer.renderImageWithDPI(pageCounter, dpi, ImageType.RGB);
            String imageFileName = pdfFilename.replace(".pdf", "") + "-" + (pageCounter++) + ".png";
            ImageIOUtil.writeImage(bim, imageFileName, dpi);
            File imageFile = new File(imageFileName);
            files.add(imageFile);
        }
        try {
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return files;
    }
}
